<template>
  <scroll-view
    :class="['c-scroll-continar', className]"
    :style="{ height: height + 'px' }"
    :scrollY="true"
    :refresherEnabled="true"
    :upperThreshold="16"
    :enhanced="true"
    :showScrollbar="false"
    :refresherTriggered="refresherTriggered"
    :refresherDefaultStyle="refresherDefaultStyle"
    :refresherBackground="refresherBackground"
    @scroll="scroll"
    @scrolltoupper="onUpper"
    @scrolltolower="onLower"
    @refresherrefresh="onRefresh"
  >
    <view class="scroll-wrap">
      <CListLoading :loading="refresherTriggered" fiexdTop></CListLoading>
      <slot></slot>
      <CListLoading :loading="lowerTriggered"></CListLoading>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, defineEmits, defineExpose } from 'vue'
import CListLoading from '@/components/c-list-loading'
import Taro from '@tarojs/taro'

const props = defineProps({
  height: {
    type: Number,
    default: 500
  },
  className: {
    type: String,
    default: ''
  },
  refresherBackground: {
    type: String,
    default: 'white'
  },
  refresherDefaultStyle: {
    type: String,
    default: 'none'
  }
})

const emit = defineEmits(['scroll', 'onRefresh', 'onUpper', 'onLower'])
const scroll = e => {
  emit('scroll', e.detail)
}

const refresherTriggered = ref(false)
const onRefresh = () => {
  setTimeout(() => scroll({ detail: { scrollTop: 0 } }), 0)
  if (refresherTriggered.value) return
  refresherTriggered.value = true
  emit('onRefresh')
  setTimeout(() => {
    refresherTriggered.value = false
  }, 2500)
}

const onUpper = e => {
  emit('onUpper', e)
}

const lowerTriggered = ref(false)
const onLower = () => {
  if (lowerTriggered.value) return
  lowerTriggered.value = true
  emit('onLower')
  setTimeout(() => {
    lowerTriggered.value = false
  }, 2000)
}

const done = () => {
  lowerTriggered.value = false
  refresherTriggered.value = false
}

defineExpose({
  done
})
</script>

<style lang="scss">
@import '@/assets/styles/custom_theme.scss';

.c-scroll-continar {
  .scroll-wrap {
    .show {
      opacity: 1;
      text-align: center;
      line-height: 60px;
    }
    .hide {
      opacity: 0;
    }
  }
}
</style>
